package cn.org.eshow.service.impl;


import cn.org.eshow.bean.query.CaptchaQuery;
import cn.org.eshow.common.CommonVar;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.dao.CaptchaDao;
import cn.org.eshow.model.Captcha;
import cn.org.eshow.model.User;
import cn.org.eshow.service.CaptchaManager;
import cn.org.eshow.util.RandomCodeUtil;
import cn.org.eshow.util.RegexUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.WebService;
import java.util.Date;
import java.util.List;

@WebService(serviceName = "CaptchaService", endpointInterface = "cn.org.eshow.service.CaptchaManager")
@Service
public class CaptchaManagerImpl extends GenericManagerImpl<Captcha, Integer> implements CaptchaManager {

    @Autowired
    CaptchaDao captchaDao;

    public CaptchaManagerImpl() {
    }

    @Autowired
    public CaptchaManagerImpl(CaptchaDao captchaDao) {
        super(captchaDao);
        this.captchaDao = captchaDao;
    }

    @Override
    public List<Captcha> list(CaptchaQuery query) {
        return captchaDao.list(query);
    }

    @Override
    public Page<Captcha> search(CaptchaQuery query) {
        return captchaDao.search(query);
    }

    @Override
    public Captcha save(String type, String code, String mobile) {
        Captcha obj = new Captcha();
        obj.setType(type);
        obj.setCode(code);
        obj.setMobile(mobile);
        obj.setState(CommonVar.CODE_UNUSED);//未使用
        return captchaDao.save(obj);
    }

    @Override
    public Captcha check(CaptchaQuery query) {
        query.setBegin(1);
        query.setPagesize(1);
        Page<Captcha> page = search(query);
        if (page.getDataList().isEmpty()) {
            return null;
        }
        return page.getDataList().get(0);
    }

    @Override
    public Captcha save(String type, String code, String email, User user) {
        Captcha object = new Captcha();
        object.setType(type);
        object.setCode(code);
        object.setEmail(email);
        object.setUser(user);
        return captchaDao.save(object);
    }

    @Override
    public Captcha updateState(Captcha captcha) {
        if (captcha == null) {
            return null;
        }
        captcha.setState(captcha.getState() == CommonVar.CODE_UNUSED ? CommonVar.CODE_USED : CommonVar.CODE_UNUSED);
        return captchaDao.save(captcha);
    }

}
